package com.sdw.message.util;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.google.gson.Gson;

/**
 * @author stevenshi
 * @version 1.0
 */
public class JSONSender {

	private final static Log log = LogFactory.getLog(JSONSender.class);

	/**
	 * @param response
	 *            向Web前台发送响应数据的HttpServletResponse对象
	 * @param src
	 *            待发送的Object数据
	 * @throws IOException
	 */
	public static void send(HttpServletResponse response, Object src) {
		Gson gson = new Gson();
		String json = gson.toJson(src);// 封装成json对象

		response.setContentType("application/json; charset=utf-8");
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = null;
		try {
			out = response.getWriter();
		} catch (IOException e) {
			log.error("format json error.", e);
		} finally {
			if (out != null) {
				out.print(json);
				out.flush();
			}
		}

	}

	public static void sendJsonp(HttpServletResponse response,
			HttpServletRequest request, Object src) {
		Gson gson = new Gson();
		String json = gson.toJson(src);// 封装成json对象

		response.setContentType("application/json; charset=utf-8");
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = null;

		String callback = request.getParameter("jsonpcallback");
		json = callback + "(" + json + ")";
		try {
			out = response.getWriter();
		} catch (IOException e) {
			log.error("format jsonp error.", e);
		} finally {
			if (out != null) {
				out.print(json);
				out.flush();
			}
		}

	}

}
